package com.pomelo.tool.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.pomelo.base.core.util.*;
import com.pomelo.tool.service.DeployService;
import com.pomelo.tool.service.GenGradleBuildService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageRowBounds;
import com.pomelo.base.core.bean.PageParam;
import com.pomelo.base.core.bean.PageResultBean;
import com.pomelo.base.core.bean.ResultBean;

/**
 * 测试环境部署
 *
 * @author biankudingcha
 * @date: 2021-10-07
 * @since 0.5.0
 */
@Controller @RequestMapping("/testDeploy") public class TestDeployController {

    /**
     * 根工作空间
     */
    @Value("${pomelo.root.workspace}") private String rootWorkspace;

    @Autowired private DeployService deployService;

    @Autowired private GenGradleBuildService ggbSV;

    private Log logger = LogFactory.getLog(this.getClass());

    /**
     * 查询项目列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryProjectList.do") @ResponseBody public PageResultBean queryProjectList() throws Exception {
        String sql = "SELECT * FROM T_HRMS_PROJECT";
        PageParam pageParam = HttpUtil.getPageParam();
        PageRowBounds page = new PageRowBounds(pageParam.getPageIndex(), pageParam.getPageSize());
        List<Map<String, Object>> rows = DbUtil.query(sql, new Object[] {}, page);
        PageResultBean pageResult = new PageResultBean();
        pageResult.setPageSize(pageParam.getPageSize());
        pageResult.setPageIndex(pageParam.getPageIndex());
        pageResult.setRows(rows);
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    /**
     * 保存项目
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveProject.do") @ResponseBody public ResultBean saveProject() throws Exception {
        String formDataJson = HttpUtil.getParameter("formData");
        Map<String, Object> formData = JsonUtil.toMap(formDataJson);
        deployService.saveProject(formData);

        return ResultBean.success();
    }

    /**
     * 删除项目
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/deleteProject.do") @ResponseBody public ResultBean deleteProject() throws Exception {
        String wids = HttpUtil.getParameter("wids");
        String[] widArray = wids.split(",");
        List<Object> params = new ArrayList<>();
        String sql = "DELETE FROM T_HRMS_PROJECT WHERE WID IN (" + CommonUtil.getJsonStr(widArray, params) + ")";
        DbUtil.execute(sql, params.toArray());
        return ResultBean.success();
    }

    /**
     * 部署
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/startUp.do") @ResponseBody public ResultBean startUp() throws Exception {
        String wid = HttpUtil.getParameter("wid");
        String sql = "SELECT COUNT(1) FROM T_HRMS_PROJECT WHERE STATE_=? AND WID<>?";
        int count = DbUtil.queryParseInt(sql, new Object[] {"1", wid});
        if (count > 0) {
            throw new RuntimeException("已有在运行的服务，无法同时运行多台");
        }
        sql = "SELECT WID, STATE_, SCHOOL_ID_, SERIAL_NUMBER_ FROM T_HRMS_PROJECT WHERE WID = ?";
        Map<String, Object> data = DbUtil.queryRow(sql, new Object[] {wid});
        logger.info(data.toString());
        if (!"1".equals(data.get("STATE_"))) {
            deployService.startUp(data);
        }
        return ResultBean.success();
    }

    /**
     * 停止服务
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/stopDeploy.do") @ResponseBody public ResultBean stopDeploy() throws Exception {
        String wid = HttpUtil.getParameter("wid");
        String sql = "SELECT WID, STATE_, SCHOOL_ID_, SERIAL_NUMBER_ FROM T_HRMS_PROJECT WHERE WID = ?";
        Map<String, Object> data = DbUtil.queryRow(sql, new Object[] {wid});
        if (CommonUtil.isEmptyMap(data)) {
            throw new Exception("未查询到部署记录");
        }
        if ("1".equals(data.get("STATE_"))) {
            deployService.shutdown(data);
        }
        return ResultBean.success();
    }

    /**
     * @Description: 重新拉取SVN应用
     * @Author: sunxin
     * @Param:
     * @Return:
     * @Date: 2021/10/20 10:29
     **/
    @RequestMapping("/reDeploy.do") @ResponseBody public ResultBean reDeploy() throws Exception {
        String wid = HttpUtil.getParameter("wid");
        String sql =
            "SELECT WID, STATE_, SCHOOL_ID_, SERIAL_NUMBER_, SVN_USERNAME_, SVN_PASSWORD_, SVN_PATH_ FROM T_HRMS_PROJECT WHERE WID = ?";
        Map<String, Object> data = DbUtil.queryRow(sql, new Object[] {wid});
        if (CommonUtil.isEmptyMap(data)) {
            throw new Exception("未查询到部署记录");
        }
        deployService.reDeploy(data);
        return ResultBean.success();
    }

}
